using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using OA.Common;
using NHibernate.Linq;

namespace OA.DAL
{
    public class  Base<T> where T:Model.Base
    {
        public ISession isession { get; set; }

        public string ModelName { get; private set; }

        public Base(ISession isession)
        {
            this.isession = isession;
            ModelName = typeof(T).Name;
        }

        protected const string tableAlias = "it";

        public virtual Result Add(T value)
        {
            Result ret = new Result(true, 1, "添加成功");
            try
            { 
                isession.Save(value);
                if (isession.Transaction.IsActive == false) isession.Flush();
            }
            catch (Exception e)
            {
                ret.count = 0;
                ret.success = false;
                ret.message = e.Message;
                throw e;
            }
            return ret;
        }

        public virtual Result Update(T value)
        {
            Result ret = new Result(true, 1, "修改成功");
            try
            {
                isession.Merge(value);
                if (isession.Transaction.IsActive == false) isession.Flush();
            }
            catch (Exception e)
            {
                ret.count = 0;
                ret.success = false;
                ret.message = e.Message;
                throw e;
            }
            return ret;
        }

        #region 删除

        public virtual Result Delete(string ids)
        {
            return DeleteByIntKey("ID", ids);
        }

        protected Result DeleteByIntKey(string key, string ids)
        {
            return DeleteByIntKey(key, ids, null);
        }

        protected Result DeleteByIntKey(string key, string ids, string where)
        {
            Result ret = new Result(false, 0, "");
            if (string.IsNullOrEmpty(ids))
            {
                ret.message = "请指定要删除的ID";
                return ret;
            }
            if (ids.IndexOf("'") >= 0)
            {
                ret.message = "请匆尝试任何SQL攻击";
                return ret;
            }
            string[] idarray = ids.Split(',');
            foreach (var id in idarray)
            {
                if (!Common.Utils.IsNumeric(id))
                {
                    ret.message = "参数错误!";
                    return ret;
                }
            }
            var w = tableAlias + "." + key + " in (" + ids + ")";
            if (!string.IsNullOrEmpty(where)) w += " and " + where;
            ret = DeleteByWhere(w);
            return ret;
        }

        protected Result DeleteByStringKey(string key, string ids)
        {
            return DeleteByStringKey(key, ids, null);
        }

        protected Result DeleteByStringKey(string key, string ids,string where)
        {
            Result ret = new Result(false, 0, "");
            if (string.IsNullOrEmpty(ids))
            {
                ret.message = "请指定要删除的ID";
                return ret;
            }
            if (ids.IndexOf("'") >= 0)
            {
                ret.message = "请匆尝试任何SQL攻击";
                return ret;
            }
            ids = "'" + ids.Replace(",", "','") + "'";
            var w = tableAlias + "." + key + " in (" + ids + ")";
            if (!string.IsNullOrEmpty(where)) w += " and " + where;
            ret = DeleteByWhere(w);
            return ret;
        }

        public virtual Result DeleteByWhere(string where)
        {
            return DeleteByWhere(where, null, null);
        }

        public virtual Result DeleteByWhere(string where, object[] ps,NHibernate.Type.IType[] types)
        {
            Result ret = new Result(false, 0, "删除失败");
            try
            {
                string hql = "from " + ModelName + " " + tableAlias + " where " + where;
                ret.count = isession.Delete(hql,ps,types);
                if (isession.Transaction.IsActive == false) isession.Flush();
                if (ret.count > 0)
                {
                    ret.success = true;
                    ret.message = "成功删除 " + ret.count.ToString() + " 条数据";
                }
            }
            catch (Exception e)
            {
                ret.message = e.Message;
                throw e;
            }
            return ret;
        }
        #endregion

        #region 查询

        public virtual T GetModel(object id)
        {
            return isession.Get<T>(id);
        }

        /// <summary>
        ///  查询
        /// </summary>
        /// <param name="where">条件，为空无条件</param>
        /// <param name="orderby">排序,为空不排序</param>
        /// <returns></returns>
        public virtual IList<T> Get()
        {
            return Get(null, null, 0, 0);
        }

        /// <summary>
        ///  查询
        /// </summary>
        /// <param name="where">条件，为空无条件</param>
        /// <param name="orderby">排序,为空不排序</param>
        /// <returns></returns>
        public virtual IList<T> Get(string where, string orderby, params object[] ps)
        {
            return Get(where, orderby,0,0, ps);
        }

        /// <summary>
        ///  查询
        /// </summary>
        /// <param name="where">条件，为空无条件</param>
        /// <param name="orderby">排序,为空不排序</param>
        /// <param name="start">起始位置,从0开始</param>
        /// <param name="length">最大数据条数，0为所有</param>
        /// <returns></returns>
        public virtual IList<T> Get(string where, string orderby, int start, int length,params object[] ps)
        {
            IList<T> ret = new List<T>();
            string hql = "from " + ModelName + " " + tableAlias;
            if (!string.IsNullOrEmpty(where)) hql += " where " + where;
            if (!string.IsNullOrEmpty(orderby)) hql += " order by " + orderby;

            IQuery query = isession.CreateQuery(hql);
            //query.SetCacheable(true);
            if (ps != null)
            {
                for (int i = 0; i < ps.Length; i++)
                {
                    query.SetParameter(i, ps[i]);
                }
            }
            if (start > 0) query.SetFirstResult(start);
            if (length > 0) query.SetMaxResults(length);
            ret = query.List<T>();
            return ret;
        }

        /// <summary>
        ///  查询总数
        /// </summary>
        /// <param name="where">条件，为空无条件</param>
        /// <returns></returns>
        public virtual int GetCount(string where, params object[] ps)
        {
            int ret = 0;
            string hql = "select count(*) from " + ModelName + " " + tableAlias;
            if (!string.IsNullOrEmpty(where)) hql += " where " + where;
            IQuery query = isession.CreateQuery(hql);
            //query.SetCacheable(true);
            if (ps != null)
            {
                for (int i = 0; i < ps.Length; i++)
                {
                    query.SetParameter(i, ps[i]);
                }
            }
            ret = Convert.ToInt32(query.UniqueResult());
            return ret;
        }
        #endregion
    }
}
